package org.monitor.controller.malog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.monitor.http.RestResult;
import org.monitor.kit.FileKit;
import org.monitor.model.MonitorStateManager;
import org.monitor.model.ServerBean;
import org.monitor.servlet.controller.Controller;

/**
 * 服务器
 * @author zhaojjd
 *
 */
public class MAServerController extends Controller {

	public void list(){
		List<ServerBean> list = new ArrayList<ServerBean>();
		String storeDir = MonitorStateManager.getServerInstance().getStoreDir().toString();
		File dir = new File(storeDir);
		if(dir.exists()){
			String[] names = dir.list();
			for (String filename : names) {
				ServerBean server = new ServerBean();
				String[] strs = filename.split("_");
				server.setIp(strs[0]);
				if(strs.length > 1){
					server.setPort(Integer.valueOf(strs[1]));
				}
				list.add(server);
			}
		}
		
		RestResult rst = new RestResult();
		rst.setData(list);
		renderJson(rst);
	}
	
	public void create(){
		getPairs().checkRequired("ip", "port");
		
		String ip = getPair("ip");
		String port = getPair("port");
		
		String storeDir = MonitorStateManager.getServerInstance().getServerDir(ip, port).toString();
		File file = new File(storeDir);
		boolean flag = true;
		if(!file.exists()){
			flag = file.mkdirs();
		}
		RestResult rst = new RestResult();
		if(!flag){
			rst.setState(-1);
			rst.setMsg("创建失败！");
		}
		renderJson(rst);
	}
	
	public void del(){
		getPairs().checkRequired("ip", "port");
		
		String ip = getPair("ip");
		String port = getPair("port");
		
		String storeDir = MonitorStateManager.getServerInstance().getServerDir(ip, port).toString();
		File file = new File(storeDir);
		
		RestResult rst = new RestResult();
		
		if(MonitorStateManager.getServerInstance().hasMonitoring(ip, port)){
			rst.setState(-1);
			rst.setMsg("当前服务器存在正在监控的对象，无法删除！");
		}else {
			boolean flag = FileKit.deleteAll(file);
			if(!flag){
				rst.setState(-1);
				rst.setMsg("删除失败！");
			}
		}
		
		renderJson(rst);
	}

}
